#!/bin/bash
# 加载环境变量
source /etc/profile

# 获取当前脚本名称
SCRIPT_NAME=$(basename "$0")
echo "当前脚本名称: $SCRIPT_NAME"

# 获取当前脚本的 PID
CURRENT_PID=$$

# 查找是否有相同的脚本正在运行（排除自己）
RUNNING_PIDS=$(pgrep -f "$SCRIPT_NAME" | grep -v "$CURRENT_PID")

if [ -n "$RUNNING_PIDS" ]; then
    echo "检测到已有相同脚本正在运行，尝试关闭..."
    echo "$RUNNING_PIDS" | xargs kill -9
    echo "已关闭旧的脚本实例。"
fi

echo "当前脚本 PID: $CURRENT_PID，继续执行..."


# 检查并释放 APT 锁
APT_LOCKS=(/var/lib/dpkg/lock /var/lib/dpkg/lock-frontend /var/lib/apt/lists/lock /var/cache/apt/archives/lock)
for lock in "${APT_LOCKS[@]}"; do
    if echo "$platform4_linuxPassword" | sudo -S fuser "$lock" >/dev/null 2>&1; then
        echo "[$(date)] 检测到 APT 锁 ($lock)，尝试释放..."
        LOCK_PID=$(echo "$platform4_linuxPassword" | sudo -S lsof -t "$lock")
        if [ -n "$LOCK_PID" ]; then
            echo "$platform4_linuxPassword" | sudo -S kill -9 "$LOCK_PID"
        fi
        echo "$platform4_linuxPassword" | sudo -S rm -f "$lock"
    fi
done


# 检查 GLIBC 版本
GLIBC_VERSIONS=$(strings /lib/aarch64-linux-gnu/libc.so.6 | grep GLIBC_)
if [[ ! $GLIBC_VERSIONS =~ "GLIBC_2.33" ]] && [[ ! $GLIBC_VERSIONS =~ "GLIBC_2.34" ]]; then
    echo "GLIBC 版本过低，检查 APT 源并更新 libc6"

    # 定义要添加的 APT 源
    APT_SOURCES=(
        "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports jammy main restricted universe multiverse"
        "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports jammy-updates main restricted universe multiverse"
        "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports jammy-security main restricted universe multiverse"
    )

    # 读取当前 sources.list 并检查是否已存在这些 APT 源
    for source in "${APT_SOURCES[@]}"; do
        if ! grep -Fxq "$source" /etc/apt/sources.list; then
            echo "$platform4_linuxPassword" | sudo -S tee -a /etc/apt/sources.list <<< "$source"
        fi
    done

    source /etc/profile

    # 更新 APT 并检查是否成功
    echo "更新 APT 源..."
    if ! echo "$platform4_linuxPassword" | sudo -S apt update; then
        echo "APT 更新失败，尝试修复..."
        echo "$platform4_linuxPassword" | sudo -S apt --fix-broken install -y
        echo "$platform4_linuxPassword" | sudo -S apt update || { echo "APT 更新仍然失败，退出脚本"; exit 1; }
    fi

    # 安装 libc6，并在失败时尝试修复
    echo "安装 libc6..."

    # 设置 debconf 选项，自动接受服务重启
    echo "$platform4_linuxPassword" | sudo -S debconf-set-selections <<< "libc6 libraries/restart-without-asking boolean true"
    
    # 设置非交互模式，避免交互提示
    export DEBIAN_FRONTEND=noninteractive
    
    # 先尝试修复可能未完成的配置
    echo "$platform4_linuxPassword" | sudo -S dpkg --configure -a
    
    # 尝试安装 libc6
    if ! echo "$platform4_linuxPassword" | sudo -S apt install -y libc6 --option=Dpkg::Options::="--force-confdef" --option=Dpkg::Options::="--force-confold"; then
      echo "libc6 安装失败，尝试修复..."
      
      # 运行 dpkg 修复
      echo "$platform4_linuxPassword" | sudo -S dpkg --configure -a
      
      # 运行 apt 修复
      echo "$platform4_linuxPassword" | sudo -S apt --fix-broken install -y
      
      # 重新安装 libc6
      if ! echo "$platform4_linuxPassword" | sudo -S apt install -y libc6 --option=Dpkg::Options::="--force-confdef" --option=Dpkg::Options::="--force-confold"; then
          echo "libc6 仍然无法安装，退出脚本"
          exit 1
        fi
      fi

echo "libc6 安装成功"

else
    echo "GLIBC 版本符合要求"
fi


# 设置 AnyDesk 安装目录
ANYDESK_DIR="/home/feibot/anydesk-6.4.2"
if [ -d "$ANYDESK_DIR" ]; then
    echo "AnyDesk 已存在，跳过下载和解压"
else
    mkdir -p "$ANYDESK_DIR"

    # 下载 AnyDesk
    cd /home/feibot || exit
    echo "正在下载 AnyDesk..."
    wget -q --show-progress https://download.anydesk.com/rpi/anydesk-6.4.2-arm64.tar.gz

    # 解压 AnyDesk
    echo "解压 AnyDesk..."
    tar -xzvf anydesk-6.4.2-arm64.tar.gz -C "$ANYDESK_DIR" --strip-components=1

    # 给予执行权限
    chmod +x "$ANYDESK_DIR/anydesk"
    echo "安装完成，可以运行 $ANYDESK_DIR/anydesk"
fi

# 关闭正在运行的 AnyDesk
echo "关闭正在运行的 AnyDesk..."
pkill -f anydesk && sleep 1

# 启动 AnyDesk
export DISPLAY=:0
echo "启动 AnyDesk..."
chmod +x "$ANYDESK_DIR/anydesk"
"$ANYDESK_DIR/anydesk" --no-fullscreen &

# 等待 AnyDesk 界面加载后调整窗口
sleep 5

# 检查 wmctrl 是否安装，失败时尝试修复
if ! command -v wmctrl &>/dev/null; then
    echo "wmctrl 未安装，正在安装..."
    if ! echo "$platform4_linuxPassword" | sudo -S apt install -y wmctrl; then
        echo "wmctrl 安装失败，尝试修复..."
        echo "$platform4_linuxPassword" | sudo -S apt --fix-broken install -y
        echo "$platform4_linuxPassword" | sudo -S apt install -y wmctrl || { echo "wmctrl 仍然无法安装，退出脚本"; exit 1; }
    fi
fi

# 调整 AnyDesk 主窗口位置和大小
echo "调整 AnyDesk 主窗口位置和大小..."
wmctrl -r "AnyDesk" -e 0,0,0,500,400

# 获取当前所有窗口的ID并存储
previous_windows=$(wmctrl -l | grep -i "AnyDesk" | awk '{print $1}')

# 监控新打开的 AnyDesk 窗口并调整大小
while true; do
    # 获取当前的所有 AnyDesk 窗口
    current_windows=$(wmctrl -l | grep -i "AnyDesk" | awk '{print $1}')

    # 找到新增的窗口
    new_windows=$(comm -13 <(echo "$previous_windows" | sort) <(echo "$current_windows" | sort))

    # 如果有新窗口，则调整其大小
    if [ -n "$new_windows" ]; then
        for window_id in $new_windows; do
            echo "检测到新窗口（ID: $window_id），调整大小..."
            wmctrl -r "AnyDesk" -e 0,0,0,500,400
        done
    fi

    # 更新 previous_windows 列表
    previous_windows="$current_windows"

    # 每隔2秒检查一次
    sleep 2
done

